<template>
  <div class="banner-container">
    <h1 class="page-title">公告轮播管理</h1>

    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAddBanner">
        <el-icon><Plus /></el-icon>
        添加轮播公告
      </el-button>
    </div>

    <!-- 轮播列表 -->
    <el-table :data="banners" style="width: 100%; margin-top: 20px" v-loading="loading" border row-key="id">
      <el-table-column prop="sortOrder" label="排序" width="80" align="center">
        <template #default="scope">
          <el-tag type="info">{{ scope.row.sortOrder }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="noticeTitle" label="公告标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="publishTime" label="发布时间" width="180" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="scope">
          <el-button size="small" :disabled="scope.$index === 0" @click="handleMoveUp(scope.row, scope.$index)">
            上移
          </el-button>
          <el-button
            size="small"
            :disabled="scope.$index === banners.length - 1"
            @click="handleMoveDown(scope.row, scope.$index)"
          >
            下移
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加轮播公告对话框 -->
    <el-dialog v-model="dialogVisible" title="选择公告添加到轮播" width="900px" :close-on-click-modal="false">
      <!-- 搜索栏 -->
      <div class="dialog-search">
        <el-input
          v-model="searchTitle"
          placeholder="输入公告标题搜索"
          clearable
          @keyup.enter="handleSearchNotices"
          @clear="handleSearchNotices"
        >
          <template #suffix>
            <el-icon class="search-icon" @click="handleSearchNotices"><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearchNotices">搜索</el-button>
      </div>

      <!-- 公告列表 -->
      <el-table
        :data="noticeList"
        style="width: 100%; margin-top: 15px"
        v-loading="noticeLoading"
        border
        max-height="400"
        @selection-change="handleNoticeSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="checkSelectable" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="公告标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag v-if="isInBanner(scope.row.id)" type="success">已在轮播</el-tag>
            <el-tag v-else type="info">未添加</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="dialog-pagination">
        <el-pagination
          v-model:current-page="noticePage"
          v-model:page-size="noticePageSize"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total, sizes, prev, pager, next"
          :total="totalNotices"
          @current-change="handleNoticePageChange"
          @size-change="handleNoticeSizeChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAdd" :disabled="selectedNotices.length === 0">
            确认添加 {{ selectedNotices.length > 0 ? `(${selectedNotices.length})` : '' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, InfoFilled } from '@element-plus/icons-vue'
import { noticeBannerAPI, noticeAPI } from '@/api'

// 轮播列表数据
const loading = ref(false)
const banners = ref([])

// 对话框相关
const dialogVisible = ref(false)
const noticeLoading = ref(false)
const noticeList = ref([])
const totalNotices = ref(0)
const noticePage = ref(1)
const noticePageSize = ref(10)
const searchTitle = ref('')
const selectedNotices = ref([])

// 获取轮播列表
const fetchBanners = async () => {
  loading.value = true
  try {
    const response = await noticeBannerAPI.getList()
    if (response.code === 200) {
      banners.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取轮播列表失败')
    }
  } catch (error) {
    console.error('获取轮播列表失败:', error)
    ElMessage.error('获取轮播列表失败')
  } finally {
    loading.value = false
  }
}

// 获取公告列表
const fetchNotices = async () => {
  noticeLoading.value = true
  try {
    const params = {
      page: noticePage.value,
      pageSize: noticePageSize.value,
    }

    if (searchTitle.value.trim()) {
      params.title = searchTitle.value.trim()
    }

    const response = await noticeAPI.getList(params)
    if (response.code === 200) {
      noticeList.value = response.data.list || []
      totalNotices.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败')
  } finally {
    noticeLoading.value = false
  }
}

// 打开添加对话框
const handleAddBanner = () => {
  dialogVisible.value = true
  noticePage.value = 1
  searchTitle.value = ''
  selectedNotices.value = []
  fetchNotices()
}

// 搜索公告
const handleSearchNotices = () => {
  noticePage.value = 1
  fetchNotices()
}

// 公告分页变化
const handleNoticePageChange = (page) => {
  noticePage.value = page
  fetchNotices()
}

// 公告页大小变化
const handleNoticeSizeChange = (size) => {
  noticePageSize.value = size
  noticePage.value = 1
  fetchNotices()
}

// 选择变化
const handleNoticeSelectionChange = (selection) => {
  selectedNotices.value = selection
}

// 检查是否已在轮播中
const isInBanner = (noticeId) => {
  return banners.value.some((banner) => banner.noticeId === noticeId)
}

// 检查是否可选择
const checkSelectable = (row) => {
  return !isInBanner(row.id)
}

// 确认添加
const handleConfirmAdd = async () => {
  if (selectedNotices.value.length === 0) {
    ElMessage.warning('请选择要添加的公告')
    return
  }

  try {
    const noticeIds = selectedNotices.value.map((item) => item.id)
    const response = await noticeBannerAPI.batchAdd(noticeIds)

    if (response.code === 200) {
      ElMessage.success('添加成功')
      dialogVisible.value = false
      fetchBanners()
    } else {
      ElMessage.error(response.message || '添加失败')
    }
  } catch (error) {
    console.error('添加轮播失败:', error)
    ElMessage.error('添加失败')
  }
}

// 切换状态
const handleStatusChange = async (row) => {
  try {
    const response = await noticeBannerAPI.updateStatus(row.id, row.status)
    if (response.code === 200) {
      ElMessage.success(row.status === 1 ? '已启用' : '已禁用')
    } else {
      // 恢复原状态
      row.status = row.status === 1 ? 0 : 1
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
    console.error('切换状态失败:', error)
    ElMessage.error('操作失败')
  }
}

// 上移
const handleMoveUp = async (row, index) => {
  if (index === 0) return

  try {
    const prevRow = banners.value[index - 1]
    const response = await noticeBannerAPI.swapSort(row.id, prevRow.id)

    if (response.code === 200) {
      ElMessage.success('上移成功')
      fetchBanners()
    } else {
      ElMessage.error(response.message || '上移失败')
    }
  } catch (error) {
    console.error('上移失败:', error)
    ElMessage.error('上移失败')
  }
}

// 下移
const handleMoveDown = async (row, index) => {
  if (index === banners.value.length - 1) return

  try {
    const nextRow = banners.value[index + 1]
    const response = await noticeBannerAPI.swapSort(row.id, nextRow.id)

    if (response.code === 200) {
      ElMessage.success('下移成功')
      fetchBanners()
    } else {
      ElMessage.error(response.message || '下移失败')
    }
  } catch (error) {
    console.error('下移失败:', error)
    ElMessage.error('下移失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除轮播公告"${row.noticeTitle}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const response = await noticeBannerAPI.delete(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchBanners()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBanners()
})
</script>

<style scoped>
.banner-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.tips {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
  padding: 8px 16px;
  background-color: #f4f4f5;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

.dialog-search {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-icon {
  cursor: pointer;
  color: #409eff;
}

.search-icon:hover {
  color: #337ecc;
}

.dialog-pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
